package xyz.iguilty.documents.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.HttpUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ObjectUtils;

import java.io.IOException;

public class ResourceUtil {

    public static final String CLASSPATH = "classpath:";

    public byte[] read(String url){
        if (ObjectUtils.isEmpty(url)){
            return null;
        }
        if (url.startsWith("http://")||url.startsWith("https://")){
           return readRemote(url);
        }else {
            return readLocal(url);
        }
    }

    private byte[] readLocal(String url){
        byte[] bytes = null;
        if (url.length()>CLASSPATH.length()&&url.startsWith(CLASSPATH)){
            try {
                bytes = FileUtil.readBytes(new ClassPathResource(url.substring(CLASSPATH.length())).getFile());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            try {
                bytes = FileUtil.readBytes(url);
            } catch (IORuntimeException e) {
                try {
                    bytes = FileUtil.readBytes(new ClassPathResource(url).getFile());
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        }
        return bytes;
    }

    private byte[] readRemote(String url){
        byte[] bytes = null;
        try {
            bytes = HttpUtil.downloadBytes(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

}
